package com.wxy.netty;

import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.EventLoop;
import io.netty.channel.nio.NioEventLoop;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.util.concurrent.GenericFutureListener;

import java.util.concurrent.*;

/**
 * @author 47868
 */
public class FutureTest {
    static ExecutorService executor = Executors.newFixedThreadPool(2);

    public static void JdkFutureTest() throws ExecutionException, InterruptedException {
        Future<Integer> future = executor.submit(new Callable() {

            @Override
            public Object call() throws Exception {
                System.out.println(Thread.currentThread().getName());
                Thread.sleep(1000);
                return 50;
            }
        });
        System.out.println(Thread.currentThread().getName()+" "+future.get());
        executor.shutdown();
    }

    public static void NettyFutureTest() throws ExecutionException, InterruptedException {
        NioEventLoopGroup loops = new NioEventLoopGroup();
        EventLoop loop = loops.next();
        io.netty.util.concurrent.Future future = loop.submit(new Callable() {

            @Override
            public Object call() throws Exception {
                System.out.println(Thread.currentThread().getName());
                Thread.sleep(1000);
                return 50;
            }
        });
//        System.out.println(Thread.currentThread().getName()+" "+future.get());
//        loops.shutdownGracefully();
        future.addListener(new GenericFutureListener<io.netty.util.concurrent.Future<Integer>>() {

            @Override
            public void operationComplete(io.netty.util.concurrent.Future<Integer> future) throws Exception {
                System.out.println(Thread.currentThread().getName()+" "+future.getNow());
                loops.shutdownGracefully();
            }

        });
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        JdkFutureTest();
        System.out.println("---------------------------------");
        NettyFutureTest();
    }
}
